﻿using System;
using System.IO;
using System.Xml.Linq;

namespace DACU.Tools
{
	public class ConfigTools
	{
		private static DateTime _lastAccessTime;
		private const int MaxCacheMinutesTime = 10;

		public static string CurrentFolder
		{
			get
			{
				var url = new Uri(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase));
				return url.LocalPath + "\\";
			}
		}

		public static string SettingsFolder
		{
			get { return CurrentFolder + @"Config\"; }
		}

		static string SettingsFileName
		{
			get { return SettingsFolder + "Params.xml"; }
		}

		public static string LibsFolder
		{
			get { return CurrentFolder + "libs\\"; }
		}

		static ConfigFile _file;
		public static ConfigFile ConfigFile
		{
			get
			{
				if (_file == null || _lastAccessTime.AddMinutes(MaxCacheMinutesTime) <= DateTime.Now)
					LoadConfig();
				return _file;
			}
		}

		public static XDocument Default
		{
			get
			{
				const string doc =@"<?xml version=""1.0"" encoding=""utf-16""?>"+
					@"<ConfigFile xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" "+
					@"Volume=""100"" Shuffle=""true"" FileLoop=""false"" ListLoop=""false"">"+
					@"<Playlist Last="""">"+
					@"<Track Id=""0"" Position=""0"" State=""BASS_ACTIVE_STOPPED"" Type=""None"" />"+
					@"</Playlist></ConfigFile>";
				XDocument xdoc = XDocument.Parse(doc, LoadOptions.SetBaseUri);
				xdoc.Save(SettingsFileName);
				return xdoc;
			}
		}

		public static void LoadConfig()
		{
			//_file = (ConfigFile) Utils.DeserializeFromFile(typeof (ConfigFile), SettingsFileName);
			var doc = XDocument.Load(SettingsFileName);
			_file = ConfigFile.FromXml(doc.Root);
			_lastAccessTime = DateTime.Now;
		}

		public static void SaveConfig()
		{
			//Utils.SerializeToFile(ConfigFile,SettingsFileName);
			ConfigFile.ToXml<XElement>().Save(SettingsFileName);
		}
	}
}
